import akshare as ak
import pandas as pd
import numpy as np
import os
from datetime import datetime
import time
import random
import requests


import requests


# 获取当前工作目录（可能受运行方式影响）
current_working_dir = os.getcwd()
data_dir = current_working_dir + "/data/"

import os

def get_unique_files(directory_path, array2):
    """
    读取目录下的所有文件名称，然后从array2中去掉已存在的元素
    
    Args:
        directory_path: 目录路径
        array2: 需要过滤的数组
    
    Returns:
        过滤后的数组
    """
    # 读取目录下的所有文件名称
    try:
        # 获取目录下所有文件和文件夹的名称
        all_items = os.listdir(directory_path)
        
        # 过滤出文件（排除文件夹）
        array1 = [item for item in all_items 
                 if os.path.isfile(os.path.join(directory_path, item))]
        #替換csv文件名
        array3 = [item.replace(".csv","") for item in array1]
        
    except FileNotFoundError:
        print(f"目录 '{directory_path}' 不存在")
        return array2
    except PermissionError:
        print(f"没有权限访问目录 '{directory_path}'")
        return array2
    
    # 从array2中去掉array1中已有的元素
    result = [item for item in array2 if item not in array3]
    
    return result



stock_all_info_pd = pd.read_csv(os.path.join(data_dir, "stock_all_info.csv"), encoding="utf_8_sig")
end_date = datetime.now().strftime("%Y%m%d")
stock_all_info_wsfbs_pd = stock_all_info_pd["代码"].str[2:]
stock_all_info_wsfbs_pd_unique = get_unique_files(os.path.join(data_dir,"stock"), stock_all_info_wsfbs_pd)
for stock_code in stock_all_info_wsfbs_pd_unique:
    #日线前复权
    time.sleep(2)
    stock_zh_a_hist_df = ak.stock_zh_a_hist(symbol=stock_code, period="daily", start_date="20200101", end_date=end_date, adjust="qfq") 
    stock_zh_a_hist_df.to_csv(os.path.join(data_dir,"stock","{}.csv".format(stock_code)), index=False, encoding="utf_8_sig")
    print("{} saved successfully!".format(stock_code))
print("前复权股票日线 saved successfully!")
